package entity

import (
	"blog/app/dto"
	"blog/app/models"
	"blog/config"
	"blog/utils"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"time"
)

// RegCheck 注册检查用户名是否重复
func RegCheck(param dto.UserRegParams) (error, int) {
	var dbUser models.UserBasic
	useModel := utils.MySqlDB.Model(&dbUser)
	if err := useModel.Where("user_name = ?", param.UserName).First(&dbUser).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 新建用户信息
			dbUser = models.UserBasic{
				UserName:      param.UserName,
				Password:      param.Password,
				Phone:         param.Phone,
				LoginTime:     time.Now(),
				HeartbeatTime: time.Now(),
				LogOutTime:    time.Now(),
				IsLogout:      false,
			}
			err := utils.MySqlDB.Model(&dbUser).Create(&dbUser).Error
			if err != nil {
				fmt.Println("创建用户信息失败", err)
				return err, config.ERROR
			}
			fmt.Println("创建用户成功", dbUser)
			return nil, config.SUCCESS
		} else {
			fmt.Println("其他错误", err)
			return nil, config.ERROR
		}
	}
	fmt.Println("查询用户已存在")
	return nil, config.ERROR
}
